package com.marvels.financial.loan.service.impl;

import com.github.pagehelper.PageHelper;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfeLoanWithholdingDao;
import com.marvels.financial.loan.dao.McfeLoanWithholdingDetailDao;
import com.marvels.financial.loan.dto.HandleWithholePaymentDTO;
import com.marvels.financial.loan.dto.McfeLoanWithholdingDTO;
import com.marvels.financial.loan.dto.McfeLoanWithholdingDetailDTO;
import com.marvels.financial.loan.dto.PaymentResponse;
import com.marvels.financial.loan.service.RepaymentService;
import com.marvels.financial.loan.service.WithholdPaymentApi;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class RepaymentServiceImpl implements RepaymentService {
	@Autowired
	private McfeLoanWithholdingDetailDao mcfeLoanWithholdingDetailDao;
	@Autowired
	private McfeCustomerLoanContractDao mcfeCustomerLoanContractDao;
	@Autowired
	private McfeLoanWithholdingDao mcfeLoanWithholdingDao;
	@Autowired
	private WithholdPaymentApi  withholdPaymentApi ;
	@Override
	public List<McfeLoanWithholdingDetailDTO> searchLoanWithholdingDetail(
			McfeLoanWithholdingDetailDTO mcfeLoanWithholdingDetailDTO) throws MarvelsBusinessException{
		if (mcfeLoanWithholdingDetailDTO != null) {
			if (mcfeLoanWithholdingDetailDTO.getCurrentPage() != null && mcfeLoanWithholdingDetailDTO.getPageSize() != null) {
				PageHelper.startPage(mcfeLoanWithholdingDetailDTO.getCurrentPage(), mcfeLoanWithholdingDetailDTO.getPageSize());
			}
		}
		return mcfeLoanWithholdingDetailDao.selectLoanWithholdingDetail(mcfeLoanWithholdingDetailDTO);
	}
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void manualServiceCharge(McfeLoanWithholdingDetailDTO mcfeLoanWithholdingDetailDTO)
			throws MarvelsBusinessException {
		if(mcfeLoanWithholdingDetailDTO==null){
			throw new MarvelsBusinessException("传入参数为空");
		}
		BigDecimal amountAct = mcfeLoanWithholdingDetailDTO.getAmountAct();//输入金额
		if(amountAct!=null&&amountAct.compareTo(BigDecimal.ZERO)==1){
			mcfeLoanWithholdingDetailDao.updateLoanWithholdingDetailById(mcfeLoanWithholdingDetailDTO);
		}else{
			throw new MarvelsBusinessException("手动输入咨询费金额不正确");
		}
		McfeLoanWithholdingDetailDTO dto = mcfeLoanWithholdingDetailDao.selectLoanWithholdingDetailById(mcfeLoanWithholdingDetailDTO);
		if(dto!=null){
			BigDecimal amount = dto.getAmount();
			if(amount!=null&&amount.compareTo(amountAct)==0){
				mcfeLoanWithholdingDetailDTO.setStatus("D1");
				mcfeLoanWithholdingDetailDao.updateLoanWithholdingDetailById(mcfeLoanWithholdingDetailDTO);
				//检查咨询费是否全部代扣成功
				McfeLoanWithholdingDetailDTO loanIdDto = new McfeLoanWithholdingDetailDTO();
				loanIdDto.setLoanId(dto.getLoanId());
				checkConsultWithholding(loanIdDto);
			}else{
//				String a = null;
//				a.equals("1");
				throw new MarvelsBusinessException("应还金额与输入金额不一致");
			}
		}else{
			throw new MarvelsBusinessException("查询到该笔详情为空");
		}
		mcfeCustomerLoanContractDao.updateContractByLoanId(mcfeLoanWithholdingDetailDTO);
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void withHoldingAgain(McfeLoanWithholdingDetailDTO mcfeLoanWithholdingDetailDTO)
			throws MarvelsBusinessException {
		if(mcfeLoanWithholdingDetailDTO ==null){
			throw new MarvelsBusinessException("传入参数为空");
		}
		if(StringUtils.isEmpty(mcfeLoanWithholdingDetailDTO.getStatus()) || "D1".equals(mcfeLoanWithholdingDetailDTO.getStatus()) || "D4".equals(mcfeLoanWithholdingDetailDTO.getStatus())){
			throw new MarvelsBusinessException("该笔流水不能发起重新代扣");
		} 
		McfeLoanWithholdingDetailDTO originDto = mcfeLoanWithholdingDetailDao.selectLoanWithholdingDetailById(mcfeLoanWithholdingDetailDTO);
		mcfeLoanWithholdingDetailDao.insertSingleLoanWithholdingDetail(originDto);//生成一条最新的
		McfeLoanWithholdingDetailDTO tmpDto = new McfeLoanWithholdingDetailDTO();
		tmpDto.setStatus("D4");
		tmpDto.setId(mcfeLoanWithholdingDetailDTO.getId());
		mcfeLoanWithholdingDetailDao.updateLoanWithholdingDetailById(tmpDto);//修改保存老数据
		if(originDto!=null&&(originDto.getAmount().subtract(originDto.getAmountAct())).compareTo(BigDecimal.ZERO)==1){
			Map<String,String> resultMap = paymentConsultingFee(originDto);//调用咨询费代扣接口
			originDto.setStatus(resultMap.get("status"));
			originDto.setResChannel(resultMap.get("payChannel"));
			originDto.setRtnResponseCode(resultMap.get("code"));
			originDto.setRtnResponseMsg(resultMap.get("msg"));
			originDto.setRtnOrderNo(resultMap.get("orderNum"));
			if("0".equals(resultMap.get("code"))){
				originDto.setAmountAct(originDto.getAmount());
			}
			mcfeLoanWithholdingDetailDao.updateLoanWithholdingDetail(mcfeLoanWithholdingDetailDTO);
			
		}else if(originDto!=null&&(originDto.getAmount().subtract(originDto.getAmountAct())).compareTo(BigDecimal.ZERO)==0){
			throw new MarvelsBusinessException("该笔流水需代扣金额为0");
		}else{
			return;
		}
		//检查咨询费是否全部代扣成功
		McfeLoanWithholdingDetailDTO loanIdDto = new McfeLoanWithholdingDetailDTO();
		loanIdDto.setLoanId(originDto.getLoanId());
		checkConsultWithholding(loanIdDto);
	}
	
	
	/**代扣咨询费
	 * @author 娄凯琦
	 * @date 2018年5月17日  
	 * @return
	 */
	private Map<String,String> paymentConsultingFee(McfeLoanWithholdingDetailDTO dto){
		MarvelsLogUtil.getInstance().info("the McfeLoanWithholdingDetail is withhold ,the loanId ====="+dto.getLoanId());
		HandleWithholePaymentDTO handleWithholePaymentDTO = new HandleWithholePaymentDTO();
		handleWithholePaymentDTO.setAmount(dto.getAmount());
		handleWithholePaymentDTO.setFundSource(dto.getFundCode());
		handleWithholePaymentDTO.setReqNo(dto.getTransctionSeq());
		handleWithholePaymentDTO.setCustName(dto.getCustName());
		handleWithholePaymentDTO.setBankName(dto.getBankName());
		handleWithholePaymentDTO.setCustBankAccountNo(dto.getBankCardNo());
		handleWithholePaymentDTO.setRemark("");
		handleWithholePaymentDTO.setCustBindPhoneNo(dto.getMobile());
		handleWithholePaymentDTO.setCustBankAcctType("1");
		handleWithholePaymentDTO.setCustId(dto.getCustCardNo());
		handleWithholePaymentDTO.setMerchantTreatyNo("");
		PaymentResponse paymentResponse =withholdPaymentApi.withholdPayment(handleWithholePaymentDTO);//咨询费代扣
		Map<String,String>	resultParam = new HashMap<String,String>();
		if(paymentResponse==null){
			resultParam.put("code", "999");
        	resultParam.put("msg", "代扣出错");
        	resultParam.put("status", "D2");
        	resultParam.put("payChannel", "");
		}else if(MarvelsConstant.TIMEOUT.equalsIgnoreCase(paymentResponse.getCode())
                || MarvelsConstant.PROCESSING.equalsIgnoreCase(paymentResponse.getCode())){
			resultParam.put("code", "999");
        	resultParam.put("msg", "代扣出错,查询超时");
        	resultParam.put("orderNum",paymentResponse.getOrderNumber());
        	resultParam.put("status", "D2");
        	resultParam.put("payChannel", paymentResponse.getChannel());
		}else if(MarvelsConstant.SUCCESS.equalsIgnoreCase(paymentResponse.getCode())) {//成功
            //返回交易码
        	resultParam.put("code", MarvelsConstant.SUCCESS);
            //返回描述
        	resultParam.put("msg", paymentResponse.getMsg());
            //响应方流水号
        	resultParam.put("orderNum",paymentResponse.getOrderNumber());
            //流水状态
        	resultParam.put("status", "D1");    	
        	//代扣成功，将金额累加到三张表中    	
        	resultParam.put("payChannel", paymentResponse.getChannel());
        }else{
        	resultParam.put("code",paymentResponse.getCode());
        	resultParam.put("msg", paymentResponse.getMsg());
        	resultParam.put("orderNum",paymentResponse.getOrderNumber());
            //流水状态
        	resultParam.put("status", "D2");
        	resultParam.put("payChannel", paymentResponse.getChannel());
        }
		return resultParam;
	}
	
	
	/**检查咨询费是否全部代扣完成
	 * @author 娄凯琦
	 * @date 2018年5月21日  
	 */
	private void checkConsultWithholding(McfeLoanWithholdingDetailDTO mcfeLoanWithholdingDetailDTO){
		//根据loanId查询
		List<McfeLoanWithholdingDetailDTO> list = mcfeLoanWithholdingDetailDao.selectLoanWithholdingDetail(mcfeLoanWithholdingDetailDTO);
		if(list!=null){
			boolean isOk = true;
			boolean isFail = true;
			for(McfeLoanWithholdingDetailDTO det:list){
				String status = det.getStatus();
				// 全为成功才不进入此
				if(!"D1".equals(status)){
					isOk = false;
				}
				// 全为失败才不进入此
				if(!"D2".equals(status)){
					isFail = false;
				}
			}
			McfeLoanWithholdingDTO mcfeLoanWithholdingDTO = new McfeLoanWithholdingDTO();
			if(isOk){
				mcfeLoanWithholdingDTO.setLoanId(mcfeLoanWithholdingDetailDTO.getLoanId());
				mcfeLoanWithholdingDTO.setStatus("S1");
			}
			if(isFail){
				mcfeLoanWithholdingDTO.setLoanId(mcfeLoanWithholdingDetailDTO.getLoanId());
				mcfeLoanWithholdingDTO.setStatus("S2");
			}
			mcfeLoanWithholdingDao.updateLoanWithholding(mcfeLoanWithholdingDTO);;
		}
	}
	@Override
	public void querywithHoldingResult(McfeLoanWithholdingDetailDTO mcfeLoanWithholdingDetailDTO)
			throws MarvelsBusinessException {
		//调用外部查询接口
	}
}
